package org.jeecg.modules.mes.produce.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.client.StockClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.produce.entity.MesAncillarytoolHeat;
import org.jeecg.modules.mes.produce.entity.MesAncillarytoolStir;
import org.jeecg.modules.mes.produce.service.IMesAncillarytoolHeatService;
import org.jeecg.modules.mes.produce.service.IMesAncillarytoolStirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 制造中心-辅料搅拌
 * @Author: jeecg-boot
 * @Date: 2020-10-16
 * @Version: V1.0
 */
@Api(tags = "制造中心-辅料搅拌")
@RestController
@RequestMapping("/produce/mesAncillarytoolStir")
@Slf4j
public class MesAncillarytoolStirController extends JeecgController<MesAncillarytoolStir, IMesAncillarytoolStirService> {
    @Autowired
    private IMesAncillarytoolStirService mesAncillarytoolStirService;
    @Autowired
    private IMesAncillarytoolHeatService mesAncillarytoolHeatService;
    @Autowired
    private SystemClient systemClient;
    @Autowired
    private StockClient stockClient;

    /**
     * 分页列表查询
     *
     * @param mesAncillarytoolStir
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-分页列表查询")
    @ApiOperation(value = "制造中心-辅料搅拌-分页列表查询", notes = "制造中心-辅料搅拌-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesAncillarytoolStir mesAncillarytoolStir,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesAncillarytoolStir> queryWrapper = QueryGenerator.initQueryWrapper(mesAncillarytoolStir, req.getParameterMap());
        queryWrapper.orderByAsc("expect_finishtime");
        Page<MesAncillarytoolStir> page = new Page<MesAncillarytoolStir>(pageNo, pageSize);
        IPage<MesAncillarytoolStir> pageList = mesAncillarytoolStirService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesAncillarytoolStir
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-添加")
    @ApiOperation(value = "制造中心-辅料搅拌-添加", notes = "制造中心-辅料搅拌-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesAncillarytoolStir mesAncillarytoolStir) {
        //搅拌之前需要提前判断回温是否已回温且回温达标

        //料号
        String ancillaryCode = mesAncillarytoolStir.getAncillaryCode();
        //根据料号查询回温状态
        LambdaQueryWrapper<MesAncillarytoolHeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MesAncillarytoolHeat::getAncillaryCode, ancillaryCode);
        MesAncillarytoolHeat heatInfo = mesAncillarytoolHeatService.getOne(wrapper);
        if ("达标".equals(heatInfo.getState())) {
            Date stirBeginTime = mesAncillarytoolStir.getStirBegintime();
            if (stirBeginTime == null) {
                return Result.error("请输入搅拌开始时间！");
            }
            String stirTime = mesAncillarytoolStir.getStirTime();
            if (StringUtils.isBlank(stirTime)) {
                return Result.error("请输入搅拌时间！");
            }
            int amount = Integer.valueOf(stirTime);
            Date finishTime = addTime(stirBeginTime, amount);
            mesAncillarytoolStir.setExpectFinishtime(finishTime);
            mesAncillarytoolStirService.save(mesAncillarytoolStir);
            return Result.ok("添加成功！");
        }
        return Result.error("回温不达标，无法搅拌");
    }

    public static Date addTime(Date date, int amount) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.MINUTE, amount);
        date = calendar.getTime();
        return date;
//		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//		 String dateString = formatter.format(date);
//		 return dateString;
    }

    /**
     * 编辑
     *
     * @param mesAncillarytoolStir
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-编辑")
    @ApiOperation(value = "制造中心-辅料搅拌-编辑", notes = "制造中心-辅料搅拌-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesAncillarytoolStir mesAncillarytoolStir) {
        //获取搅拌开始时间
        long stirBegintime = mesAncillarytoolStir.getStirBegintime().getTime();
        //获取当前时间
        long current = System.currentTimeMillis();
        //推算搅拌时间
        long heatTime = current - stirBegintime;
        long minute = heatTime / (60 * 1000);
        if (minute < Long.parseLong(mesAncillarytoolStir.getStirTime())) {
            //搅拌时间不够
            mesAncillarytoolStir.setStirState("不达标");
        } else if (minute > Long.parseLong(mesAncillarytoolStir.getStirLimit())) {
            //搅拌超时
            mesAncillarytoolStir.setStirState("超时");
        } else {
            //搅拌达标
            mesAncillarytoolStir.setStirState("达标");
        }
        mesAncillarytoolStir.setEndStirtime(new Date());
        mesAncillarytoolStirService.updateById(mesAncillarytoolStir);
        return Result.ok(mesAncillarytoolStir.getStirState());
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-通过id删除")
    @ApiOperation(value = "制造中心-辅料搅拌-通过id删除", notes = "制造中心-辅料搅拌-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesAncillarytoolStirService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-批量删除")
    @ApiOperation(value = "制造中心-辅料搅拌-批量删除", notes = "制造中心-辅料搅拌-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesAncillarytoolStirService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "制造中心-辅料搅拌-通过id查询")
    @ApiOperation(value = "制造中心-辅料搅拌-通过id查询", notes = "制造中心-辅料搅拌-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesAncillarytoolStir mesAncillarytoolStir = mesAncillarytoolStirService.getById(id);
        if (mesAncillarytoolStir == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesAncillarytoolStir);
    }

    /**
     * 远程调用，查询是否有搅拌记录且状态为达标
     * @param sn
     * @return
     */
    @GetMapping(value = "/queryAncillaryBySn")
    public MesAncillarytoolStir queryAncillaryBySn(@RequestParam(name = "sn", required = true) String sn) {
        QueryWrapper<MesAncillarytoolStir> mesaStirQueryWrapper = new QueryWrapper<>();
        mesaStirQueryWrapper.eq("ancillary_sn",sn);
        mesaStirQueryWrapper.eq("stir_state","达标");
        mesaStirQueryWrapper.orderByDesc("create_time");
        List<MesAncillarytoolStir> list = mesAncillarytoolStirService.list(mesaStirQueryWrapper);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesAncillarytoolStir
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesAncillarytoolStir mesAncillarytoolStir) {
        return super.exportXls(request, mesAncillarytoolStir, MesAncillarytoolStir.class, "制造中心-辅料搅拌");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesAncillarytoolStir.class);
    }

}
